package com.zhouxin.customview.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.zhouxin.customview.extensions.dp2px
import kotlin.math.cos
import kotlin.math.sin


/**
 * Copyright©
 * FileName: DashBoardView
 * Author: ZhouXin
 * Date: 2022/6/3
 * Description:仪表盘
 * Tips:
 * 使用PathDashPathEffect()来绘制刻度
 * 使用PathMeasure()来测量path的长度
 */
private const val OPEN_ANGLE = 120f
private const val MARK = 4.5
private const val DASH_COUNT = 15
private val DASH_WIDTH = 2f.dp2px
private val DASH_HEIGHT = 10f.dp2px
private val DASH_RADIUS = 5f.dp2px
private val PATH_WIDTH = 3f.dp2px
private val RADIUS = 150f.dp2px
private val LENGTH = 120f.dp2px
class DashBoardView(context: Context, attrs: AttributeSet) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val path = Path()
    private val dash = Path()
    private lateinit var pathEffect: PathDashPathEffect

    init {
        paint.strokeWidth = PATH_WIDTH
        paint.style = Paint.Style.STROKE
        dash.addRect(0f, 0f, DASH_WIDTH, DASH_HEIGHT, Path.Direction.CW)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        path.reset()
        path.addArc(
            width / 2f - RADIUS,
            height / 2f - RADIUS,
            width / 2f + RADIUS,
            height / 2f + RADIUS,
            90 + OPEN_ANGLE / 2f,
            360 - OPEN_ANGLE
        )
        val pathMeasure = PathMeasure(path, false)
        pathEffect = PathDashPathEffect(
            dash,
            (pathMeasure.length - DASH_WIDTH) / DASH_COUNT,
            0f,
            PathDashPathEffect.Style.ROTATE
        )
    }

    override fun onDraw(canvas: Canvas) {
        //画弧
        canvas.drawPath(path, paint)
        //画刻度
        paint.pathEffect = pathEffect
        canvas.drawPath(path, paint)
        paint.pathEffect = null
        //画中心
        canvas.drawCircle(
            width / 2f,
            height / 2f,
            DASH_RADIUS,
            paint
        )
        //画指针
        canvas.drawLine(
            width / 2f - DASH_RADIUS + PATH_WIDTH / 2f,
            height / 2f - DASH_RADIUS + PATH_WIDTH / 2f,
            width / 2f + LENGTH * cos(markToRadians(MARK).toFloat()),
            height / 2f + LENGTH * sin(markToRadians(MARK).toFloat()),
            paint
        )
    }

    private fun markToRadians(mark: Double) =
        Math.toRadians(90 + OPEN_ANGLE / 2f + (360 - OPEN_ANGLE) / DASH_COUNT * mark)
}